package com.Input;

import com.Input.KeyBoard.KeyPress;
import com.Input.KeyBoard.KeyRelease;
import com.Stage.mapStage;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;


public class InputManager implements Runnable {
    private static final Set<KeyCode> pressed = Collections.newSetFromMap(new ConcurrentHashMap<>());
    private final ConcurrentLinkedQueue<KeyCode> released = new ConcurrentLinkedQueue<>();
    private final KeyPress keyPress;
    private final KeyRelease keyRelease;
    private final List<Scene> scenes;

    public InputManager() {
        keyPress = new KeyPress();
        keyRelease = new KeyRelease();
        scenes = new ArrayList<>();
    }

    @Override
    public void run() {
        registerListener();
        while (true) {
            KeyCode keyCode;
            //这里可以处理 有关于按键的释放 比如释放J算算作一次攻击
            while ((keyCode = keyRelease.pollEvent()) != null) {
                released.add(keyCode);
            }
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public void setScene(List<mapStage> mapStageList) {
        for (mapStage mapStage : mapStageList) {
            if (mapStage != null) {
                scenes.add(mapStage.getGameScene().getScene());
            }
        }
    }

    public void registerListener() {
        //主线程实现按键监听
        for (Scene scene : scenes) {
            scene.addEventFilter(KeyEvent.KEY_PRESSED, keyPress);
            scene.addEventFilter(KeyEvent.KEY_RELEASED, keyRelease);
        }
    }


    public static Set<KeyCode> getPressed() {
        return pressed;
    }

    public ConcurrentLinkedQueue<KeyCode> getReleased() {
        return released;
    }
}
